<template>
  <div class="admin-management">
    <div class="header">
      <h2>管理员管理</h2>
      <a-button type="primary" @click="showModal">
        <template #icon><plus-outlined /></template>
        添加管理员
      </a-button>
    </div>

    <a-table :columns="columns" :data-source="adminList" :loading="loading">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个管理员吗？"
              @confirm="handleDelete(record)"
            >
              <a class="danger">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
        <template v-if="column.key === 'role'">
          <a-tag :color="record.role === '超级管理员' ? 'red' : 'blue'">
            {{ record.role }}
          </a-tag>
        </template>
        <template v-if="column.key === 'lastLoginTime'">
          {{ record.lastLoginTime ? new Date(record.lastLoginTime).toLocaleString() : '-' }}
        </template>
      </template>
    </a-table>

    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item
          label="密码"
          name="password"
          v-if="modalTitle === '添加管理员'"
        >
          <a-input-password
            v-model:value="formState.password"
            placeholder="请输入密码"
          />
        </a-form-item>
        <a-form-item label="角色" name="role">
          <a-select v-model:value="formState.role" placeholder="请选择角色">
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="super_admin">超级管理员</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { admins as adminsApi } from '@/services/api'

const loading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref('添加管理员')
const adminList = ref([])
const formRef = ref(null)

const columns = [
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '角色',
    dataIndex: 'role',
    key: 'role'
  },
  {
    title: '最后登录时间',
    dataIndex: 'lastLoginTime',
    key: 'lastLoginTime'
  },
  {
    title: '操作',
    key: 'action'
  }
]

const formState = reactive({
  id: undefined,
  username: '',
  email: '',
  password: '',
  role: 'admin'
})

const rules = {
  username: [{ required: true, message: '请输入用户名' }],
  email: [
    { required: true, message: '请输入邮箱' },
    { type: 'email', message: '请输入有效的邮箱地址' }
  ],
  password: [{ required: true, message: '请输入密码' }],
  role: [{ required: true, message: '请选择角色' }]
}

const fetchAdmins = async () => {
  loading.value = true
  try {
    const response = await adminsApi.getList()
    adminList.value = response.data || []
  } catch (error) {
    console.error('获取管理员列表失败:', error)
    message.error('获取管理员列表失败')
  } finally {
    loading.value = false
  }
}

const showModal = () => {
  modalTitle.value = '添加管理员'
  formState.id = undefined
  formState.username = ''
  formState.email = ''
  formState.password = ''
  formState.role = 'admin'
  modalVisible.value = true
}

const handleEdit = (record) => {
  modalTitle.value = '编辑管理员'
  formState.id = record.id
  formState.username = record.username
  formState.email = record.email
  formState.role = record.role
  modalVisible.value = true
}

const handleDelete = async (record) => {
  try {
    await adminsApi.delete(record.id)
    message.success('删除成功')
    fetchAdmins()
  } catch (error) {
    console.error('删除管理员失败:', error)
    message.error('删除管理员失败')
  }
}

const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    if (formState.id) {
      const updateData = { ...formState }
      delete updateData.password
      await adminsApi.update(formState.id, updateData)
      message.success('更新成功')
    } else {
      await adminsApi.create(formState)
      message.success('添加成功')
    }
    modalVisible.value = false
    fetchAdmins()
  } catch (error) {
    console.error('保存管理员失败:', error)
    message.error('保存管理员失败')
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
}

onMounted(() => {
  fetchAdmins()
})
</script>

<style scoped>
.admin-management {
  padding: 24px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.danger {
  color: #ff4d4f;
}
</style> 